#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>

#include "include.h"
#include "HelperUtils.h"
#include "ServerMain.h"

#include "ftpserver.h"

/* Entry point to the ftp server program.
 *  - Fork a child to does the main ftp server job.
 *  - The parent do a scanf for QUIT.
 */

int main(int argc, char** argv){
    // Test for correct number of arguments
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <Server Port> <Root Directory>\n", argv[0]);
        exit(1);
    }
    // Process command line arguments
    int serverPort = atoi(argv[1]);
    char* documentRoot = argv[2];

    // Ignore SIGINT, use QUIT instead
    signal(SIGINT, SIG_IGN);

    // Fork the child
    pid_t childPid;
    int childReturnValue;
    char *command = NULL;
    size_t commandSize = 0;

    switch( childPid = fork() ) {
    case -1:
        // Error
        dieWithError("FATAL: fork() failed.");
    case 0:
        // This is the child
        #if DEBUG == 1
        fprintf(stderr, "DEBUG: Child spawned with PID: %d\n", getpid());
        #endif

        childReturnValue = serverMain(serverPort, documentRoot);
        exit(childReturnValue);
    default:
        // This is parent
        while (1) {
            command = NULL;
            commandSize = 0;
            if (getLongLine(&command, &commandSize) != 0)
                dieWithError("FATAL: getLongLine() failed.");
            if (strcmp(command, "QUIT") == 0) {
                #if DEBUG == 1
                fprintf(stderr, "DEUBG: Sending SIGTERM to child.\n");
                #endif
                // Send SIGTERM to tell ServerMain to exit
                if ( kill(childPid, SIGTERM) == -1) {
                    dieWithError("FATAL: kill() failed.");
                }
                free(command);
                wait(NULL);
                break;
            }
            free(command);
        }
    }
    return 0;
}

